package org.snusmumr.android.media.dialog;

import org.snusmumr.android.media.R;
import org.snusmumr.android.media.data.ContactAPI;
import org.snusmumr.android.media.data.MediaColumns;
import org.snusmumr.android.media.util.Utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SelectContactDialog extends Dialog {
	private static final String TAG = SelectContactDialog.class.getSimpleName();
	private SimpleCursorAdapter cursorAdapter;
	private ListView contactsView;
	private OnSelectListener listener;
	
	public interface OnSelectListener {
		public void onSelect(String contactId, String displayName);
	}
	

	public SelectContactDialog(Context context, OnSelectListener listener) {
		super(context);
		this.listener = listener;
		
		setTitle(R.string.select_contact_dlg_title);
		setContentView(R.layout.select_contact_dlg);
		contactsView = new ListView(this.getContext());
		contactsView.setId(android.R.id.list);
		LinearLayout scroll = (LinearLayout) findViewById(R.id.select_contact_scroll);
		scroll.addView(contactsView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		final EditText filterEdit = (EditText) findViewById(R.id.select_contact_search_view);
		filterEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				Cursor c = cursorAdapter.runQueryOnBackgroundThread(s);
				cursorAdapter.getCursor().close();
				cursorAdapter.changeCursor(c);
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			
			@Override
			public void afterTextChanged(Editable s) {}
		});
		
		final ContactAPI contacts = ContactAPI.getAPI();
		contacts.setContentResolver(getContext().getContentResolver());
		final String displayNameColumn = contacts.getMetaData().displayName();
		Cursor cursor = contacts.getContactsCursor(null, null, displayNameColumn);
		cursorAdapter = new SimpleCursorAdapter(context, 
				android.R.layout.simple_list_item_1, 
				cursor, new String[]{MediaColumns.DISPLAY_NAME}, 
				new int[]{android.R.id.text1});
		cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
			@Override
			public Cursor runQuery(CharSequence constraint) {
				String selection = null;
				if(constraint.length() > 1)
					selection = "lower(" + MediaColumns.DISPLAY_NAME + ") like '%"+
					constraint.toString().toLowerCase() + "%'";
				Cursor cursor = contacts.getContactsCursor(selection, null, displayNameColumn); 
				return cursor;
			}
		});
		contactsView.setAdapter(cursorAdapter);
		contactsView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				cursorAdapter.getCursor().move(position-cursorAdapter.getCursor().getPosition());
				int indexId = cursorAdapter.getCursor().getColumnIndex(MediaColumns._ID);
				int indexName = cursorAdapter.getCursor().getColumnIndex(MediaColumns.DISPLAY_NAME);
				SelectContactDialog.this.listener.onSelect(cursorAdapter.getCursor().getString(indexId), 
						cursorAdapter.getCursor().getString(indexName));
				SelectContactDialog.this.dismiss();
			}
		});
		
		Button createContact = (Button) findViewById(R.id.btn_create_contact);
		createContact.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//TODO show create user dialog
				final String displayName = filterEdit.getText().toString();
				Log.i(TAG, "contact name: " + displayName);
				if(Utils.isEmpty(displayName)) {
					Toast.makeText(SelectContactDialog.this.getOwnerActivity().getApplicationContext(), 
							"_Please enter contact name", Toast.LENGTH_SHORT);
					return;
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(SelectContactDialog.this.getOwnerActivity().getApplicationContext());
				builder.setMessage("_Are you sure you want to create a new contact?")
				.setPositiveButton(R.string.btn_dlg_save, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						long id = contacts.insertContact(displayName);
						if(id > 0) {
							SelectContactDialog.this.listener.onSelect(String.valueOf(id), displayName);
						}
					}
				}).setNegativeButton(R.string.btn_dlg_cancel, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
			}
		});
	}
	
	
	@Override
	protected void onStop() {
		super.onStop();
		if(! cursorAdapter.getCursor().isClosed())
			cursorAdapter.getCursor().close();
	}

}
